# PREFIX=
CC=$(PREFIX)gcc
CFLAGS=-std=gnu11 -g -Wall -Wfatal-errors
CXX=$(PREFIX)g++
CXXFLAGS=-std=gnu++11 -g -Wall -Wfatal-errors
LD=$(PREFIX)g++
LDFLAGS=

# 头文件路径
INC=

# 需要编译的源文件
SRCS=

# 库的链接路径
LIBSFLODERS=test/googletest/v1.12.1/lib

# 依赖的库
LIBS+=pthread
LIBS+=gtest

# 缓存目录
TARGET=target

# 所有源文件对应的.o文件
OBJS=$(patsubst %,$(TARGET)/%.o,$(SRCS))

# 头文件依赖
DEPS=$(patsubst %,$(TARGET)/%.o.d,$(SRCS))

# 添加头文件依赖
-include $(DEPS)

# 生成的程序
BIN=bin

run::$(BIN)
	@./$<

$(BIN):$(OBJS)
	@echo "LD    $@"
	@$(LD) $(LDFLAGS) $^ -o $@ $(addprefix -L,$(LIBSFLODERS)) $(addprefix -l,$(LIBS))

$(filter %.c.o,$(OBJS)):$(TARGET)/%.c.o:%.c
	@echo "CC    $<"
	@mkdir -p $(dir $@)
	@$(CC) $(CFLAGS) $(addprefix -I,$(INC)) -c -o $@ $< -MMD -MP -MF $@.d

$(filter %.cpp.o,$(OBJS)):$(TARGET)/%.cpp.o:%.cpp
	@echo "CXX   $<"
	@mkdir -p $(dir $@)
	@$(CXX) $(CXXFLAGS) $(addprefix -I,$(INC)) -c -o $@ $< -MMD -MP -MF $@.d

# 编译gtest
test/googletest/v1.12.1/include/gtest/gtest.h \
test/googletest/v1.12.1/lib/libgtest.a:
	@rm     -rf test/googletest/v1.12.1
	@mkdir  -p  test/googletest/v1.12.1
	@tar    xf  test/googletest/googletest-release-1.12.1.tar.gz \
	        -C  test/googletest/
	@mkdir  -p  test/googletest/googletest-release-1.12.1/build
	@cd         test/googletest/googletest-release-1.12.1/build && \
	 cmake      .. \
	            -DCMAKE_INSTALL_PREFIX="$(PWD)/test/googletest/v1.12.1" \
	   			-DCMAKE_C_COMPILER="$(CC)" \
	   			-DCMAKE_CXX_COMPILER="$(CXX)" \
	   			-DCMAKE_CXX_FLAGS="-std=gnu++11" \
	   			-DCMAKE_BUILD_TYPE=Release \
	   			-Dgtest_force_shared_crt=ON
	@cd         test/googletest/googletest-release-1.12.1/build && \
	 make       && \
	 make       install
	@rm     -rf test/googletest/googletest-release-1.12.1

.PHONY:clean
clean:
	@rm -rf $(BIN) $(OBJS)